package com.angis.fx.activity.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.IBinder;
import android.widget.Toast;

import com.angis.fx.data.PictureInfo;
import com.angis.fx.util.UploadUtil;

public class PicUploadService extends Service {

	@Override
	public void onCreate() {
		super.onCreate();

	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		PictureInfo lInfo = (PictureInfo) intent.getExtras().get("picinfo");
		if(lInfo.getPicrecordid()==null){
			lInfo.setPicrecordid("");
		}
		Bitmap bitmap=null;
		try {

			Toast.makeText(this, "开始上传图片", Toast.LENGTH_LONG).show();
			// ProgressDialog lProgress = ProgressDialog.show(this, "",
			// "上传中...",
			// true);
			File file = new File(lInfo.getUpLoadPath());
			if (file.exists()) {
				bitmap = BitmapFactory.decodeFile(lInfo.getUpLoadPath());
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, 100, out);
				
				lInfo.setFilebody(out.toByteArray());
				lInfo.setFileExtension(".jpg");
				lInfo.setFilename(file.getName().substring(0, file.getName().lastIndexOf(".")));
				bitmap.recycle();
				String result = UploadUtil
						.uploadPic(lInfo);
				
				lInfo=null;
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				 factory.setNamespaceAware(true);
		         XmlPullParser xpp = factory.newPullParser();

		         xpp.setInput( new StringReader (result) );
		         String returnText="";
		         int eventType = xpp.getEventType();
		         while (eventType != XmlPullParser.END_DOCUMENT) {
		        	 if(eventType == XmlPullParser.TEXT) {
		                 System.out.println("result:  "+xpp.getText());
		                 returnText=xpp.getText();
		             }
		        	 eventType = xpp.next();
		         }
		         System.out.println();
				if ("1".equals(returnText)) {
					file.renameTo(new File(android.os.Environment
							.getExternalStorageDirectory()
							+ "/fx/upLoad/" + file.getName()));
					Toast.makeText(this, "图片上传成功", Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(this, "图片上传失败，请稍后再试！", Toast.LENGTH_LONG)
							.show();
				}

				// lProgress.dismiss();
				
			}
		} catch (Exception e) {
			Toast.makeText(this, "图片上传失败，请稍后再试！", Toast.LENGTH_LONG)
			.show();
		} finally {
			if(bitmap!=null)
				bitmap.recycle();
			System.gc();
			this.stopSelf();
		}
	}

	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}

}
